<template>
    <div class="app-container">
        <div style="margin-top: 15px">
            <el-form :inline="true" size="mini" label-width="100px">
                <el-form-item label="输入搜索：">
                    <el-input v-model="listQuery.keywords" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="">
                    <el-button
                            size="mini"
                            type="primary"
                            class="btn-add"
                            @click="getList()">
                        查询
                    </el-button>
                    <el-button
                            size="mini"
                            type="primary"
                            class="btn-add"
                            @click="showDialog('add')">
                        新增
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-tree
                    class="my-tree"
                    :data="data"
                    node-key="articleId"
                    default-expand-all
                    :props="props"
                    :expand-on-click-node="false">
                                  <span class="custom-tree-node" slot-scope="{ node, data }" style="width:100%;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">
                                    <span style="font-size:12px">{{ node.label }}</span>
                                    <span>
                                          <el-button
                                                  type="text"
                                                  size="mini"
                                                  @click="showDialog('edit',data)">
                                            编辑
                                          </el-button>
                                          <el-button
                                                  type="text"
                                                  size="mini"
                                                  @click="handleDelete(data)">
                                            删除
                                          </el-button>
                                    </span>
                                  </span>
            </el-tree>
        </div>
            <el-dialog :close-on-click-modal="false"
                       :title="title"
                       :beforeClose="handleClose"
                       :visible.sync="dialogVisible"
                       width="600px">
                <div class="manageForm-div" v-if="show">
                    <el-form :model="fileForm" size="mini" label-width="100px" :rules="rules" ref="fileForm" style="height:100%;">
                        <el-form-item label="文档名称：" prop="articleTitle">
                            <el-input v-model="fileForm.articleTitle" placeholder="" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="文档父级：" prop="roleName">
                            <el-cascader
                                    v-model="fileForm.parentId"
                                    :options="data2"
                                    :props="{ checkStrictly: true,value:'articleId',label:'articleTitle',emitPath:false}"
                                    clearable>
                            </el-cascader>
                        </el-form-item>
                        <el-form-item label="排序：" prop="sortOrder">
                            <el-input v-model="fileForm.sortOrder" placeholder="" style="width:100px" ></el-input>
                        </el-form-item>
                        <el-form-item label="上传文件：" prop="articleFile">
                            <el-upload action="https://upload.qiniup.com" :http-request="sliderRequest" :limit="2" :on-change="handleChange" :file-list="fileList" :on-preview="preview">
                                <el-button size="small" type="primary">点击上传</el-button>
                                <el-input type="hidden" v-model="fileForm.articleFile"/>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                </div>
                <span slot="footer" class="dialog-footer">
                        <el-button  @click="handleClose" size="medium">取消</el-button>
                        <el-button type="primary" @click="handleConfirm" size="medium"  :loading="btnLoading">保存</el-button>
                </span>
            </el-dialog>
    </div>

</template>
<script>
    import {delRoles,articleList,editArticle,delArticle} from '@/api/management'
    import {getQiniuToken,} from '@/api/partner'
    import axios from 'axios'
    import Tinymce from '@/components/Tinymce'
    import store from '@/store'
    const defaultListQuery = {
        keywords:''
    };
    const defaultFileForm = {
        articleId:0,
        parentId:'',
        articleTitle:'',
        articleFile:'',
        sortOrder:'',
    };
    export default {
        name: "managementSetting",
        data(){
            return{
                listQuery: Object.assign({ classId:this.$route.query.classId}, defaultListQuery),
                fileForm:JSON.parse(JSON.stringify(defaultFileForm)),
                rules: {
                    articleTitle: [
                        {required: true, message: '请输入文章名称', trigger: 'blur'},
                    ],
                    parentId: [
                        {required: true, message: '请选择父级', trigger: 'change'},
                    ],
                    sortOrder:[
                        {required: true, message: '请输入排序', trigger: 'blur'},
                    ],
                    articleFile:[{required: true, message: '请上传文章', trigger: 'change'},],
                },
                list:[],
                listLoading: false,
                activeIndex:null,
                show:true,
                btnLoading:false,
                roles:store.getters.roles ? store.getters.roles : [],
                data : [],
                props: {
                    label: 'articleTitle',
                    children: 'children'
                },
                uploadToken:'',
                imgDomain:'',
                fileName:'',
                fileList:[],
                fileUrl:'',
                data2:[],
                dialogVisible:false,
                title:''

            }
        },
        components: {Tinymce},
        created() {
            this.getList();
            this.getUploadToken();
        },
        filters: {

        },
        methods:{
            //获取七牛TOKEN
            getUploadToken(){
                getQiniuToken().then((res)=>{
                    this.uploadToken = res.token;
                    this.imgDomain = res.domain
                })
            },
            //上传文件重写
            sliderRequest(upload) {
                // 文件上传自行处理上传
                // 创建FormData对象 添加相关上传参数
                const formData = new FormData()
                // 文件对象
                formData.append('file', upload.file)
                // key 文件名处理，这样的话七牛会识别文件时什么类型
                let timestamp=new Date().getTime();
                let fileName = timestamp + upload.file.name
                formData.append('key', fileName)
                // token
                formData.append('token', this.uploadToken)//这个postData,要在data数据里面进行定义的，，，我这里调接口使用的是vue的方式
                // 上传文件
                // onUploadProgress 查看axios文档 https://github.com/axios/axios
                axios.post("https://upload.qiniup.com", formData, {
                    onUploadProgress: (event) => {
                        // 监听上传进度
                        event.percent = event.loaded / event.total * 100
                        upload.onProgress(event)
                    }
                }).then((response) => {
                    if (response.status === 200) {
                        let res = response.data;
                        this.fileForm.articleFile = this.imgDomain+res.key;
                    }else{
                        this.$message.error('上传失败');
                    }
                }).catch((err) => {
                    // 调用组件上传失败方法
                    this.$message.error('上传失败');
                })
            },

            handleChange(file, fileList) {
                this.fileList = fileList.slice(-1);
            },
            preview(file){
                window.open(this.fileForm.articleFile)
            },

            handleClose(){
                this.$refs.fileForm.clearValidate();
                this.dialogVisible = false;
            },

            showDialog(type,data){
                this.dialogVisible = true;
               if(type=='add'){
                   this.title = '新建文档';
                   this.fileForm.articleId = 0;
                   this.fileForm.parentId = '';
                   this.fileForm.articleTitle = '';
                   this.fileForm.articleFile = '';
                   this.fileForm.sortOrder = '';
                   this.fileList = [];
               }else{
                   this.title = '编辑文档';
                   this.fileForm.articleId = data.articleId;
                   this.fileForm.parentId = data.parentId== 0 ? -1 : data.parentId;
                   this.fileForm.articleTitle = data.articleTitle;
                   this.fileForm.articleFile = data.articleFile;
                   this.fileForm.sortOrder = data.sortOrder;
                   this.fileList = [];
                   if(data.articleFile !=''){
                       this.fileList.push({name:data.articleFile,url:data.articleFile});
                   }
               }

            },
            handleDelete(item){
                this.$confirm('确定删除该文档吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delArticle({articleId:item.articleId}).then(()=>{
                        this.getList();
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },



            //获取文章列表
            getList(){
                this.dataLoading = true;
                return  articleList(this.listQuery).then((res)=>{
                            this.data = res;
                            let newData = [{articleId:-1,articleTitle:'一级',parentId:1,articleFile:''}];
                            if(this.data.length > 0){
                                this.data = this.forTree(res);
                                this.data.forEach((el)=>{
                                    newData.push(el)
                                });
                            }

                            this.data2 = newData;
                            this.dataLoading = false
                })
            },
            //去除不要的children
            forTree(list){
                let newList = list;
                if(newList.length){
                    for (let i = 0; i<newList.length; i++){
                        if(newList[i].children && newList[i].children.length > 0){
                            this.forTree(newList[i].children)
                        }else{
                            delete newList[i].children;
                        }
                    }
                    return newList
                }
            },


            //新增编辑
            handleConfirm(){
                this.$refs.fileForm.validate((valid) => {
                    if (valid) {
                        this.btnLoading = true;
                        let data = {};
                        data.articleId = this.fileForm.articleId;
                        data.classId = this.$route.query.classId;
                        data.parentId = this.fileForm.parentId == -1 ? 0 : this.fileForm.parentId;
                        data.articleTitle = this.fileForm.articleTitle;
                        data.articleFile = this.fileForm.articleFile;
                        data.sortOrder = this.fileForm.sortOrder;
                        editArticle(data).then(response => {
                            this.btnLoading = false;
                            this.$message({
                                message: '提交成功',
                                type: 'success',
                                duration: 1000
                            });
                            this.getList();
                            this.handleClose();
                        }).catch(()=>{
                            this.btnLoading = false;
                        })
                    }
                });
            },

            //删除角色
            delRoleItem(item){
                this.$confirm('确定删除角色?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delRoles({roleId:item.roleId,rf:true}).then(()=>{
                        this.getList();
                        this.show = false;
                        this.activeIndex = null;
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    });

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

        }

    }
</script>

<style lang="scss">
    .custom-tree-node{
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-right: 8px;
        font-size:12px;
        .label-span{
            font-size: 12px;
            color: #666666;
        }

    }



</style>
